package com.hm.health.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.goodix.activity.FileBrowserActivity;
import com.goodix.comsdk.entity.MeasureResult;
import com.goodix.comsdk.sdk.OnHBDDataListener;
import com.goodix.comsdk.testsdk.IHBDTestClient;
import com.goodix.libromablecom.sdk.cardiff.CardiffEvkConfigUtils;
import com.goodix.utils.SPUtils;
import com.goodix.utils.ToastUtils;
import com.hm.health.MyApplication;
import com.hm.health.R;
import com.hm.health.Utils.Constans;
import com.hm.health.adapter.DeviceConfigAdapter;
import com.hm.health.entity.DeviceConfigBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeviceConfigDeliveryActivity extends BaseActivity {
    public static final String TAG = "DeviceConfigDeliveryActivity";

    public static final int REQUEST_GET_OUT_DIR_PATH = 1;
    public static final String PEFS_KEY_GET_DEVICE_CONFIG_PATH = "pefs_key_get_device_config_path";
    public static final String ARG_SET_DEVICE_CONFIG_ID_AND_NAME = "ARG_SET_DEVICE_CONFIG_ID_AND_NAME";
    public static final String ARG_SEND_DEVICE_CONFIG_TO_MCU = "ARG_SEND_DEVICE_CONFIG_TO_MCU";
    public static final String ARG_GET_SEND_DEVICE_CONFIG_RESULT = "ARG_GET_SEND_DEVICE_CONFIG_RESULT";

    @BindView(R.id.btn_load)
    Button mBtnLoad;
    @BindView(R.id.rv_device_configs)
    RecyclerView mRvDeviceConfigs;
    @BindView(R.id.btn_send)
    Button mBtnSend;
    @BindView(R.id.tv_config_path)
    TextView mTvFilePath;

    private DeviceConfigAdapter mConfigAdapter;
    private List<DeviceConfigBean> mDeviceConfigBeans = new ArrayList<>();
    private String mConfigPath;
    private DeviceConfigBean mCurrentConfig;
    private WorkThread mWorkThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_config_delivery);
        ButterKnife.bind(this);
        initView();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        setCenterTitle(R.string.send_device_config);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    private void initView() {
        initActionBar();
        mConfigAdapter = new DeviceConfigAdapter(mContext, mDeviceConfigBeans);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL,false);
        mRvDeviceConfigs.setLayoutManager(layoutManager);
        mRvDeviceConfigs.setAdapter(mConfigAdapter);
    }

    @OnClick({R.id.btn_load})
    void onBtnLoadClicked(View v) {
        String lastBrowserPath = (String) SPUtils.get(mContext,
                PEFS_KEY_GET_DEVICE_CONFIG_PATH, Constans.GOODIXHBD_FOLDER);
        FileBrowserActivity.startBrowser(this, REQUEST_GET_OUT_DIR_PATH,
                true, "", lastBrowserPath);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_GET_OUT_DIR_PATH:
                mConfigPath = data.getStringExtra(FileBrowserActivity.EXTRA_KEY_PATH);
                mTvFilePath.setText(mConfigPath);
                SPUtils.put(mContext, PEFS_KEY_GET_DEVICE_CONFIG_PATH, mConfigPath);
                String[] fileNames = listConfigFiles(mConfigPath);
                for (String v : fileNames) {
                    mDeviceConfigBeans.add(new DeviceConfigBean(0,v));
                }
                mConfigAdapter.notifyDataSetChanged();
                break;
        }
    }

    public static String[] listConfigFiles(String path) {
        File dir = new File(path);
        List<String> configs = new ArrayList<>();
        if (null == dir.list()) {
            return new String[0];
        }

        for (String name : dir.list()) {
            if (!name.isEmpty()) {
                configs.add(name);
            }
        }

        String[] dest = new String[configs.size()];
        configs.toArray(dest);
        return dest;
    }

    @OnClick({R.id.btn_send})
    void onBtnSendClicked(View v) {

        for (DeviceConfigBean bean : mDeviceConfigBeans) {
            bean.setStatus(DeviceConfigBean.STATUS_READY);
            bean.setProgress(0);
        }
        mConfigAdapter.notifyDataSetChanged();

        mWorkThread = new WorkThread();
        mWorkThread.start();
    }

    class WorkThread extends Thread {

        @Override
        public void run() {
            IHBDTestClient ihbdTestClient = MyApplication.getHBDTestClient();
            ihbdTestClient.registerHBDDataListener(mOnHBDDataListener);

            runOnUiThread(() -> {
                mBtnSend.setEnabled(false);
                mBtnLoad.setEnabled(false);
                mRvDeviceConfigs.setEnabled(false);
            });

            for (DeviceConfigBean bean : mDeviceConfigBeans) {
                if (!bean.isSelected()) {
                    continue;
                }

                if (isInterrupted()) {
                    break;
                }

                mCurrentConfig = bean;

                bean.setStatus(DeviceConfigBean.STATUS_SENDING);
                runOnUiThread(() -> mConfigAdapter.notifyDataSetChanged());

                // Set device config id
                ihbdTestClient.setRunTimeFlag(ARG_SET_DEVICE_CONFIG_ID_AND_NAME,
                        String.format(Locale.ENGLISH,"%d, %s", bean.getId(), bean.getFileName()));

                // Set config
                String strDriverConfig = CardiffEvkConfigUtils.getDriverConfig(mConfigPath, bean.getFileName());
                ihbdTestClient.setRunTimeFlag(ARG_SEND_DEVICE_CONFIG_TO_MCU, strDriverConfig);

                // Determine whether the configuration is successfully sent
                String result = ihbdTestClient.getRunTimeFlag(ARG_GET_SEND_DEVICE_CONFIG_RESULT);
                if (result.toUpperCase().compareTo(Constans.SUCCESS) != 0) {
                    bean.setStatus(DeviceConfigBean.STATUS_ERROR);
                    runOnUiThread(() -> ToastUtils.showLongToastMessage(mContext, result));
                    break;
                } else {
                    bean.setStatus(DeviceConfigBean.STATUS_SUCCESS);
                }
            }

            ihbdTestClient.unRegisterHBDDataListener(mOnHBDDataListener);

            runOnUiThread(() -> {
                mBtnSend.setEnabled(true);
                mBtnLoad.setEnabled(true);
                mRvDeviceConfigs.setEnabled(true);
                mConfigAdapter.notifyDataSetChanged();
            });
        }
    }

    OnHBDDataListener mOnHBDDataListener = new OnHBDDataListener() {
        @Override
        public void onDataChanged(String dataType, int[] dataArr) {
            if (dataType.equals("DATA_TYPE_DEVICE_CONFIG_SEND_PROGRESS")) {
                if (null != mCurrentConfig) {
                    mCurrentConfig.setProgress(dataArr[0]);
                }
                runOnUiThread(() -> mConfigAdapter.notifyDataSetChanged());
            }
        }

        @Override
        public void onMeasureResult(MeasureResult result) {

        }
    };
}
